<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
  Document   : pay_pal
  Created on : 27.06.2013., 16.21.18
  Author     : Sasa
  Description:
 */


class Pay_pal extends CI_Controller {
    
    public function __construct()
    {
        parent::__construct();
        
        $this->load->model('payment_mod');
        $this->load->model('users_mod');
    }

    public function ipnlistener()
    {
      echo "<html>";
      // read the post from PayPal system and add 'cmd'
      $req = 'cmd=_notify-validate';
      foreach ($_POST as $key => $value) {
          $value = urlencode(stripslashes($value));
          $req .= "&$key=$value";
      }
      // post back to PayPal system to validate
      $header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
      // If testing on Sandbox use: 
       $header .= "Host: www.sandbox.paypal.com:443\r\n";
      //$header .= "Host: ipnpb.paypal.com:443\r\n";
      $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
      $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
      if (strpos('ssl://www.sandbox.paypal.com', 'sandbox') !== FALSE && function_exists('openssl_open')) {
          $fp = fsockopen('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
        }
        else {
          // The old "normal" way of validating an IPN.
          $fp = fsockopen('ssl://www.sandbox.paypal.com', 80, $errno, $errstr, 30);
      }
      // If testing on Sandbox use:
      //$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
      //$fp = fsockopen ('ssl://ipnpb.paypal.com', 443, $errno, $errstr, 30);
      // assign posted variables to local variables
      $item_name          = $_POST['item_name'];
      $item_number        = $_POST['item_number'];
      $payment_status     = $_POST['payment_status'];
      $payment_amount     = $_POST['mc_gross'];
      $payment_currency   = $_POST['mc_currency'];
      $txn_id             = $_POST['txn_id'];
      $receiver_email     = $_POST['receiver_email'];
      $payer_email        = $_POST['payer_email'];
      if (!$fp) {
       // HTTP ERROR
      } else {
          fputs ($fp, $header . $req);
          while (!feof($fp)) {
              $res = fgets ($fp, 1024);
              if (strcmp ($res, "VERIFIED") == 0) {
                  // check the payment_status is Completed
                  // check that txn_id has not been previously processed
                  // check that receiver_email is your Primary PayPal email
                  // check that payment_amount/payment_currency are correct
                  
                  // Validate payment (Check unique txnid & correct price)
                        $valid_txnid = $this->payment_mod->check_txnid($txn_id);
//                        //$valid_price = $this->payment_mod->check_price($payment_amount, $item_name);
//                        // PAYMENT VALIDATED & VERIFIED!
                       if ($valid_txnid /* && $valid_price */) {
                          
                         //$mail_Body = "VALID TNX \n\n";
                            $data['transaction_id'] = $txn_id;
                            $data['user_id'] = $item_number;//$this->session->userdata('user_id');
                            $data['date'] = date("Y-m-d H:i:s",time());
                            $data['status'] = $payment_status;
                            $data['provider'] = "paypal";
                            $data['ip_address'] = $this->session->userdata('ip_address');
                            $data['error'] = "";
                            $data['extra'] = $item_name;
                            $data['amount'] = $payment_amount;
                            
                            $coins_ind = $item_name . "_coins";
                            $coins=$this->config->item($coins_ind);
                            
                            $orderid = $this->payment_mod->updatePayments($data);
                            if ($orderid) {
                                // Payment has been made & successfully inserted into the Database                          
                              $this->users_mod->updateCoins($coins,$data['user_id']);
                            } else {
                                // Error inserting into DB
                                // E-mail admin or alert user
                            }
                        } else {
                            // Payment made but data has been changed
                            // E-mail admin or alert user
                        }
                  
                  // process payment
                  $mail_From = "From: paypal@datyy.de";
                  $mail_To = "milojevic.sasa@gmail.com";
                  $mail_Subject = "VERIFIED IPN";
                  $mail_Body = $req;
                  foreach ($_POST as $key => $value){
                      $emailtext .= $key . " = " .$value ."\n\n";
                  }
                  $emailtext .= "\n\n------------------------------------\n";
                  foreach ($data as $key => $value){
                      $emailtext .= $key . " = " .$value ."\n\n";
                  }
                  mail($mail_To, $mail_Subject, $emailtext . "\n\n" . $mail_Body."\n\n Coins = $coins " , $mail_From);
              }
              else if (strcmp ($res, "INVALID") == 0) {
                  // log for manual investigation
                  $mail_From = "From: paypal@datyy.de";
                  $mail_To = "milojevic.sasa@gmail.com";
                  $mail_Subject = "INVALID IPN";
                  $mail_Body = $req;
                  foreach ($_POST as $key => $value){
                      $emailtext .= $key . " = " .$value ."\n\n";
                  }
                  mail($mail_To, $mail_Subject, $emailtext . "\n\n" . $mail_Body, $mail_From);
              }
          }   // while end
       fclose ($fp);
      }
      echo "</html>";
    }
}